package com.trip.api;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.ConstraintViolationException;

import com.trip.exception.ServiceException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.method.HandlerMethod;

@ControllerAdvice
public class ExceptionHandlerAdvice {

	private static final Logger logger=LoggerFactory.getLogger(ExceptionHandlerAdvice.class);

	@ExceptionHandler(value = Exception.class)
	public ResponseEntity<ControllerResult<Boolean>> exception(Exception ex, HttpServletRequest request, HttpServletResponse response, HandlerMethod handler) {

		if(ex instanceof ServiceException){
			logger.warn(ex.getMessage(),ex);
			return ResponseEntity.ok().body(ControllerResult.failed(ex));
		}else if(ex instanceof ConstraintViolationException || ex instanceof MethodArgumentNotValidException){
			//JSR-303,JSP-349
			logger.debug("Validation failed",ex);
			return ResponseEntity.ok().body(ControllerResult.failed(ex));
		}else{
			logger.error(ex.getMessage(),ex);
		}

		return ResponseEntity.badRequest().body(ControllerResult.failed(ex));
	}
	
}
